<script setup lang="ts">
import chain from '@/common/lib/chain'; // 导入区块链相关的函数库
import { Balance } from '@/types/tokens'; // 导入代币余额类型定义
import { Transfer, TransferRecord } from '@/types/transcation'; // 导入转账和交易记录类型定义

const { t } = useI18n(); // 使用国际化功能

const walletStore = useWalletStore(); // 使用钱包存储仓库
const recentVisible = ref(false); // 控制是否显示最近交易记录的弹窗
const selectTokenVisible = ref(false); // 控制是否显示选择代币下拉列表的弹窗

// 创建响应式对象来存储转账相关信息
const transfer = reactive({
  sender: '', // 转出账户
  receiver: '', // 接收账户
  amount: undefined, // 转账金额
  memo: '', // 备注信息
  token: {
    symbol: '', // 代币符号
    contract: '', // 代币合约类型
    precision: 4, // 代币精度
  }
} as Transfer);

const targeMaxAmount = ref(0); // 目标最大转账金额

// 初始化数据
const route = useRoute(); // 使用路由
onBeforeMount(() => {
  const currentSystemToken = useChainStore().currentNetwork.token; // ?????// 获取当前系统代币信息
  // 设置转账信息的代币类型等参数
  transfer.token = {
    symbol: (route.query.symbol as string) || currentSystemToken.symbol,
    contract: (route.query.contract as string) || currentSystemToken.contract,
    precision: Number(route.query.precision) || currentSystemToken.precision,
  }
  transfer.amount = Number(route.query.amount) || undefined; // 设置转账金额

  // 遍历用户钱包中的代币，获取目标代币的余额和精度信息
  walletStore.currentUserTokens.forEach((row) => {
    if (row.contract == transfer.token.contract && row.symbol == transfer.token.symbol) {
      targeMaxAmount.value = row.amount;
      transfer.token.precision = row.precision;
    }
  });

  transfer.sender = tool.briefAccount(walletStore.currentWallet.name, 14, 8); // 设置转出账户的简略信息

  getBalance(); // 获取账户余额
});

// 验证接收账户信息
const isShowMemo = ref(true); // 是否显示备注信息
const receiverError = ref(''); // 接收账户验证错误信息
const checkReceiver = async () => {
  if (!transfer.receiver) return (receiverError.value = t('wallet.emptyReceiver')); // 检查接收账户是否为空
  if (transfer.receiver == walletStore.currentWallet.name) return (receiverError.value = t('wallet.transferSelf')); // 检查是否转账给自己

  // 如果接收账户长度为42，说明是合约地址，不需要备注
  if (transfer.receiver.length == 42) isShowMemo.value = false;
  // 如果接收账户长度不为42且大于12，则需要备注
  else if (transfer.receiver.length != 42 && transfer.receiver.length > 12)
    return (receiverError.value = t('wallet.errorReceiver')); // 长度不符合要求，提示错误
  else {
    isShowMemo.value = true;
    // 查询接收账户信息，确认其存在
    let accountData = await chain.getApi().getAccount(transfer.receiver);
    if (accountData == null) return (receiverError.value = t('wallet.accountNotExist')); // 如果账户信息不存在，则提示错误
  }
  receiverError.value = ''; // 清空错误信息
};

// 选择最近的交易记录
const handleSelectTransfer = (tr: TransferRecord) => {
  recentVisible.value = false; // 关闭最近交易记录弹窗
  transfer.receiver = tr.account; // 设置接收账户为选择的记录中的账户
  transfer.memo = tr.memo; // 设置备注信息为选择的记录中的备注
  if (transfer.token) {
    // todo something
  }
  receiverError.value = ''; // 清空接收账户验证错误信息
  checkReceiver(); // 验证接收账户信息
};

// 验证转账金额
const quantityError = ref(''); // 转账金额验证错误信息
const checkQuantity = () => {
  const quantity = transfer.amount == null || isNaN(transfer.amount) ? 0 : transfer.amount; // 获取转账金额
  if (quantity == 0) return (quantityError.value = t('wallet.emptyAmount')); // 如果金额为0，提示错误
  if (quantity < 0) return (quantityError.value = t('wallet.emptyAmount')); // 如果金额小于0，提示错误
  quantityError.value = ''; // 清空错误信息
};

// 切换代币
const handleChangeToken = (coin: Balance) => {
  // 更新转账信息中的代币相关参数
  transfer.token = {
    symbol: coin.symbol,
    contract: coin.contract,
    precision: coin.precision,
  }

  targeMaxAmount.value = coin.amount; // 更新目标最大金额

  selectTokenVisible.value = false; // 关闭选择代币弹窗
  transfer.amount = 0; // 重置转账金额为0
  getBalance(); // 获取账户余额
};

// 获取账户余额
const getBalance = async () => {
  const balance = await chain.getApi().getCurrencyBalance(transfer.token.contract, walletStore.currentWallet.name, transfer.token.symbol); // 调用接口获取账户余额
  console.log("1:" + transfer.token.contract,walletStore.currentWallet.name, transfer.token.symbol)
  if (balance) {
    targeMaxAmount.value = Number(balance.split(' ')[0]); // 解析余额并更新目标最大金额
  }
};

// 验证转账信息并显示确认弹窗
const confirmVisible = ref(false); // 控制是否显示确认弹窗
const checkSubmit = () => {
  checkReceiver(); // 验证接收账户信息
  checkQuantity(); // 验证转账金额
  if (receiverError.value || quantityError.value) return; // 如果存在错误信息，不继续执行

  confirmVisible.value = true; // 显示确认弹窗
};
</script>
<template>
    <div class="full-router">
        <div class="full-inner">
            <page-header :title="$t('wallet.transfer')"></page-header>

            <div class="cover-content _effect">
                <form>
                    <!-- from account -->
                    <div class="transfer-title">{{ $t('wallet.paymentAccount') }}</div>
                    <div class="transfer-input">
                        <n-input
                            :disabled="true"
                            v-model:value="transfer.sender"
                            class="rounded-[5px] h-[46px] leading-[46px] pl-[5px]"
                        ></n-input>
                    </div>

                    <!-- receiver account -->
                    <div class="transfer-title flex justify-between items-center">
                        {{ $t('wallet.receiverAccount') }}
                        <icon-history
                            theme="filled"
                            size="16"
                            fill="#666"
                            class="cursor-pointer"
                            @click="recentVisible = true"
                        />
                    </div>
                    <div class="transfer-input">
                        <div class="flex flex-col">
                            <n-input
                                @blur="checkReceiver"
                                v-model:value="transfer.receiver"
                                :placeholder="$t('wallet.enterPasteAccount')"
                                class="rounded-[5px] h-[46px] leading-[46px] pl-[5px]"
                            ></n-input>
                            <span class="self-end mt-1 h-6 text-xs text-yellow-300">
                                {{ receiverError }}
                            </span>
                        </div>
                    </div>

                    <!-- quantity -->
                    <div class="transfer-title">
                        {{ $t('wallet.amount') }}
                    </div>
                    <div class="transfer-input">
                        <div class="flex flex-col">
                            <div class="flex justify-between">
                                <n-button
                                    @click="selectTokenVisible = true"
                                    class="symbol-button rounded-none  rounded-tl-[5px] rounded-bl-[5px]"
                                >
                                    {{ transfer.token.symbol }}
                                    <icon-down-one theme="filled" size="14" fill="#4a4a4a" class="ml-1" />
                                </n-button>
                                <n-input-number
                                    class="bg-color"
                                    style="background-color: red !important;"
                                    @blur="checkQuantity"
                                    v-model:value="transfer.amount"
                                    :min="0"
                                    :precision="transfer.token.precision"
                                    :step="0.1"
                                    :max="targeMaxAmount"
                                    :placeholder="targeMaxAmount + ' ' + transfer.token.symbol"
                                />
                                <n-button
                                    @click="
                                        transfer.amount = targeMaxAmount;
                                        checkQuantity();
                                    "
                                    class="all-button rounded-none rounded-tr-[5px] rounded-br-[5px]"
                                >
                                    {{ $t('wallet.all') }}
                                </n-button>
                            </div>
                            <span class="self-end mt-1 h-6 text-xs text-yellow-300">
                                {{ quantityError }}
                            </span>
                        </div>
                    </div>

                    <!-- memo -->
                    <div class="transfer-title" v-show="isShowMemo">{{ $t('wallet.remark') }}（Memo）</div>
                    <div class="transfer-input" v-show="isShowMemo">
                        <n-input
                            v-model:value="transfer.memo"
                            placeholder=""
                            class="rounded-[5px] h-[46px] leading-[46px] pl-[5px] mb-[20px]"
                        ></n-input>
                    </div>

                    <!-- submit -->
                    <div class="transfer-buttons">
                        <n-button type="primary" @click="checkSubmit" round class="primary-button mt-[70px]">
                            {{ $t('wallet.transfer') }}
                        </n-button>
                    </div>
                </form>
            </div>
        </div>

        <!-- recent transfer -->
        <recent-transfer
            :isShow="recentVisible"
            @select="handleSelectTransfer"
            @close="recentVisible = false"
        ></recent-transfer>

        <!-- change token -->
        <select-coin
            :isShow="selectTokenVisible"
            @close="selectTokenVisible = false"
            @changeToken="handleChangeToken"
        ></select-coin>

        <!-- input password -->
        <transfer-confirm
            :isShow="confirmVisible"
            :title="$t('wallet.transferInfo')"
            :transfer="transfer"
            @close="confirmVisible = false"
        ></transfer-confirm>
    </div>
</template>

<style lang="scss" scoped>
form {
    display: flex;
    flex-direction: column;
    align-items: center;
}

:deep(.n-input-wrapper){
  z-index: 20;
}

:deep(.n-input__border){
  background-color: #ecf5ff;
}

.selectedToken-count-tip {
    font-size: 18px;
    margin-left: 12px;
    color: #ffffff;
    letter-spacing: 0;
}

.transfer {
    font-family: PingFang SC;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
}

.transfer-title {
    margin-top: 22px;
    width: 340px;
    height: 24px;
    line-height: 24px;
    font-size: 14px;
    color: #333;
    letter-spacing: 0;
}
.transfer-input {
    margin-top: 8px;
    height: 46px;
    width: 340px;
  .bg-color{
    background-color: #F5F5F5 !important;
  }
    .transfer-input-all {
        cursor: pointer;
        font-size: 10px;
        width: 45px;
    }

    :deep(.n-input__input-el) {
        height: 46px !important;
    }

    :deep(.n-button--default-type) {
        height: 46px !important;
    }
}

.transfer-buttons {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100px;
    left: 0;
    right: 0;
    bottom: 0;
    .primary-button {
        bottom: 40px;
        height: 50px;
        width: 300px;
    }
}

.n-button__border {
    border-right: none !important;
}

.symbol-button {
    padding: 0 10px;
    overflow: hidden;
    margin-right: -1px;
}

.all-button {
    border-left: none !important;
    overflow: hidden;
    margin-left: -1px;
}

.confirm-box {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 999;
    width: 100%;
    height: 100%;
    z-index: 100;
    background-color: rgba(0, 0, 0, 0.75);
    display: flex;
    flex-direction: column-reverse;
}
</style>